package com.richest.api.controller.user;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.richest.api.controller.form.UserInfoForm;
import com.richest.api.service.IUserService;
import com.richest.api.utils.Constant;
import com.richest.api.utils.OssUploadUtil;
import com.richest.api.utils.RedisUtils;
import com.richest.api.utils.SMSUtil;
import com.richest.bean.UserBean;
import com.richest.util.CallResults;
import com.richest.util.DateUtils;
import com.richest.util.MD5Util;
import com.richest.util.StringUtil;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;

/**
 * 用户表 后端接口
 * 
 * @author zhaohongchao
 * @email 70375739@qq.com
 * @date 2019-03-06 14:18:39
 */
@RestController
@RequestMapping("/userController")
@Api(value = "用户管理接口")
@EnableAutoConfiguration
public class ApiUserController {
	@Autowired
	private IUserService userService;

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 发送验证码
	 */
	@RequestMapping(value = "sendCodeResetPass", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "修改信息发送短信验证码", value = "修改信息发送短信验证码", httpMethod = "GET")
	@ApiImplicitParam(name = "phone", value = "手机号码", required = true, paramType = "query", dataType = "String")
	public CallResults sendCode(@RequestParam String phone) {
		// ValidatorUtils.validateEntity(phone);
		if (redisUtils.get(Constant.RESET_PASS_SMS_OVERTIME_KEY + phone) != null) {
			return CallResults.error("发送验证码比较频繁，等一分钟之后再试试");
		}
		String number = RandomUtil.randomNumbers(6);
		SMSUtil.sendSMS(phone, "尊敬的用户：您的校验码：" + number + "，工作人员不会索取，请勿泄漏。", "0");
		redisUtils.set(Constant.RESET_PASS_SMS_CODE_KEY + phone, number, 60 * 15);
		redisUtils.set(Constant.RESET_PASS_SMS_OVERTIME_KEY + phone, number, 60 * 1);
		return CallResults.ok("验证码获取成功").put("data", number);
	}

	/**
	 * 修改密码
	 */
	@RequestMapping(value = "resetPass", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "修改密码", value = "修改密码", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "password", value = "新密码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "confirmPassword", value = "确认密码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query", dataType = "String") })
	public CallResults resetPass(@RequestParam Long userId, @RequestParam String password,
			@RequestParam String confirmPassword, @RequestParam String code) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);
		String phone = userBean.getPhone();
		Assert.notBlank(code, "短信验证码不能为空");
		String codeRedis = redisUtils.get(Constant.RESET_PASS_SMS_CODE_KEY + phone);
		if (codeRedis == null) {
			return CallResults.error("验证码已经失效，请重新获取");
		}
		if (!code.equals(codeRedis)) {
			return CallResults.error("输入验证码有误，请重新填写");
		}

		if (password == null || "".equals(password)) {
			return CallResults.error("新密码不能为空");
		}
		if (confirmPassword == null || "".equals(confirmPassword)) {
			return CallResults.error("请确认新密码");
		}
		if (!password.equals(confirmPassword)) {
			return CallResults.error("二次密码输入不一致,请重新输入新密码");
		}
		userBean.setPassword(MD5Util.string2MD5(password));
		userBean.setUpdate_time(DateUtils.getNowTime());
		userBean.setUpdate_by(userBean.getPhone());
		userService.update(userBean);
		return CallResults.ok("修改密码成功");
	}

	@RequestMapping(value = "setHeadPortrait", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "设置头像", value = "设置头像", httpMethod = "POST")
	@ApiImplicitParams({ @ApiImplicitParam(name = "file", value = "文件体", required = true, dataType = "MultipartFile"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "type", value = "文件类型:1-广告详情；2-店铺分类；3-活动详情；4用户头像；5-菜品图片；6-店铺图片", required = true, paramType = "query", dataType = "String") })
	public CallResults setImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId,
			@RequestParam("type") String type) throws IOException {
		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);
		if (null == userBean) {
			return CallResults.error("不存在有效的用户信息");
		}
		JSONObject result = OssUploadUtil.ossupload(type, String.valueOf(userId), file);

		if (!"200".equals(result.getString("code"))) {
			return CallResults.error("头像设置失败");
		}

		userBean.setPic_img(result.getString("url"));
		userBean.setUpdate_time(DateUtils.getNowTime());
		userBean.setUpdate_by(userBean.getPhone());
		userService.update(userBean);
		return CallResults.ok("头像设置成功");
	}

	/**
	 * 设置昵称
	 */
	@RequestMapping(value = "setNickName", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "设置昵称", value = "设置昵称", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "nickName", value = "昵称", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long") })
	public CallResults setNickName(@RequestParam String nickName, @RequestParam Long userId) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);
		userBean.setUser_name(nickName);
		userBean.setUpdate_time(DateUtils.getNowTime());
		userBean.setUpdate_by(userBean.getPhone());
		userService.update(userBean);
		return CallResults.ok("昵称设置成功");

	}

	/**
	 * 实名认证
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "realNameAuth", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "实名认证", value = "实名认证", httpMethod = "POST")
	@ApiImplicitParams({

			@ApiImplicitParam(name = "idCardFrontImg", value = "身份证正面", required = true, dataType = "MultipartFile"),
			@ApiImplicitParam(name = "idCardBackImg", value = "身份证反面", required = true, dataType = "MultipartFile"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "realName", value = "真实姓名", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "idCard", value = "身份证号", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "type", value = "文件类型:1-广告详情；2-店铺分类；3-活动详情；4用户头像；5-菜品图片；6-店铺图片", required = true, paramType = "query", dataType = "String") })
	public CallResults realNameAuth(@RequestParam("idCardFrontImg") MultipartFile idCardFrontImg,
			@RequestParam("idCardBackImg") MultipartFile idCardBackImg, @RequestParam("userId") Long userId,
			@RequestParam("realName") String realName, @RequestParam("idCard") String idCard,
			@RequestParam("type") String type) throws IOException {

		JSONObject jsonIdCardFront = OssUploadUtil.ossupload(type, String.valueOf(userId), idCardFrontImg);
		JSONObject jsonIdCardBack = OssUploadUtil.ossupload(type, String.valueOf(userId), idCardBackImg);

		if (!"200".equals(jsonIdCardFront.getString("code")) || !"200".equals(jsonIdCardBack.getString("code"))) {
			return CallResults.error("实名认证失败");
		}

		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);
		userBean.setReal_name(realName);
		userBean.setId_card(idCard);
		userBean.setIdcard_front_img(jsonIdCardFront.getString("url"));
		userBean.setIdcard_back_img(jsonIdCardBack.getString("url"));
		userBean.setUpdate_time(DateUtils.getNowTime());
		userBean.setUpdate_by(userBean.getPhone());
		userService.update(userBean);
		return CallResults.ok("实名认证通过");
	}

	@RequestMapping(value = "getUserInfo", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "获取用户信息", value = "获取用户信息", httpMethod = "POST")
	@ApiImplicitParam(name = "form", value = "获取用户信息", required = true, dataType = "UserInfoForm")
	public CallResults getUserInfo(@RequestBody UserInfoForm form) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(form.getUser_id());
		userBean.setPhone(form.getPhone());
		userBean = userService.selectOne(userBean);

		return CallResults.ok().put("data", userBean);
	}

	@RequestMapping(value = "bindingWeiXin", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "绑定微信", value = "绑定微信", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "open_id", value = "open_id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "union_id", value = "union_id", required = true, paramType = "query", dataType = "String") })
	public CallResults bindingWeiXin(@RequestParam Long userId, @RequestParam String open_id,
			@RequestParam String union_id) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);
		if (null != userBean) {
			userBean.setOpenid(open_id);
			userBean.setUnionid(union_id);
			userBean.setUpdate_time(DateUtils.getNowTime());
			userBean.setUpdate_by(userBean.getPhone());
			userService.update(userBean);
		} else {
			userBean = new UserBean();
			userBean.setOpenid(open_id);
			userBean.setUnionid(union_id);
			userBean.setRegeist_time(DateUtils.getNowTime());
			userBean.setCreate_by(open_id);
			userService.insert(userBean);
		}

		return CallResults.ok().put("data", userBean);
	}

	/**
	 * 修改手机号码
	 */
	@RequestMapping(value = "resetPhone", produces = "application/json;charset=UTF-8")
	@ApiOperation(notes = "修改手机号码", value = "修改手机号码", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "newPhone", value = "新手机号码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "query", dataType = "String") })
	public CallResults resetPhone(@RequestParam Long userId, @RequestParam String newPhone, @RequestParam String code) {
		UserBean userBean = new UserBean();
		userBean.setUser_id(userId);
		userBean = userService.selectOne(userBean);

		if (StringUtil.isNullOrEmpty(code)) {
			return CallResults.error("短信验证码不能为空");
		}
		String codeRedis = redisUtils.get(Constant.RESET_PASS_SMS_CODE_KEY + newPhone);
		if (codeRedis == null) {
			return CallResults.error("验证码已经失效，请重新获取");
		}
		if (!code.equals(codeRedis)) {
			return CallResults.error("输入验证码有误，请重新填写");
		}
		userBean.setPhone(newPhone);
		userBean.setUpdate_time(DateUtils.getNowTime());
		userBean.setUpdate_by(userBean.getPhone());
		userService.update(userBean);
		return CallResults.ok("修改手机号码成功");
	}
}
